package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.enums.StockWarnStatusEnums;
import com.ytjj.qmyx.supplychain.common.model.ProductSpecStockWarningVO;
import com.ytjj.qmyx.supplychain.common.model.request.StockWarningRequest;
import com.ytjj.qmyx.supplychain.common.model.response.SanTongResponse;
import com.ytjj.qmyx.supplychain.common.utils.EncryptUtil;
import com.ytjj.qmyx.supplychain.common.utils.HttpClientUtil;
import com.ytjj.qmyx.supplychain.mapper.NotifyUrlInfoMapper;
import com.ytjj.qmyx.supplychain.mapper.OrdersMapper;
import com.ytjj.qmyx.supplychain.mapper.ProductMapper;
import com.ytjj.qmyx.supplychain.mapper.StockWarningMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxNotifyUrlInfo;
import com.ytjj.qmyx.supplychain.mapper.entity.YxOrders;
import com.ytjj.qmyx.supplychain.mapper.entity.YxStockWarning;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StockWarningService {

    @Resource
    private StockWarningMapper stockWarningMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private NotifyUrlInfoMapper notifyUrlInfoMapper;

    @Value("${santong.account:}")
    private String stAccount;
    @Value("${santong.password:}")
    private String stPassword;
    @Value("${santong.url:}")
    private String stUrl;
    //库存预警短信开关 0-关闭  1-开启
    @Value("${sendStockWarnSwitch:0}")
    private Integer sendStockWarnSwitch;

    public CommonPage list(StockWarningRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<YxStockWarning> yxStockWarnings = stockWarningMapper.list(request);
        return CommonPage.restPage(yxStockWarnings);
    }

    /**
     * 定时任务:检查商品规格库存,低于商品库存预警值发短信通知供应商
     */
    public void verifySpecStock() {
        //获取预警中的库存预警数据
        List<YxStockWarning> yxStockWarnings = stockWarningMapper.selectAll();
        List<Integer> supplySpecIds = yxStockWarnings.stream().filter(item ->item.getWarnStatus() == StockWarnStatusEnums.ING.getStatus()).map(YxStockWarning::getSupplySpecId).collect(Collectors.toList());
        //获取状态为上架且规格库存小于预警值的商品,排除正在预警的规格id
        List<ProductSpecStockWarningVO> productSpecStockWarningVOList = productMapper.selectByStatus(supplySpecIds);
        //当前时间一个月前
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        //过去一月
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = format.format(m);
        //获取今天的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String day = simpleDateFormat.format(new Date());

        //遍历新增预警数据或修改预警数据
        productSpecStockWarningVOList.stream().forEach(item ->{
            //获取商品规格近一个月的销量
            Example ordersExample = new Example(YxOrders.class);
            ordersExample.createCriteria().andEqualTo("productSpecId",item.getSupplySpecId()).andGreaterThanOrEqualTo("orderDate",mon);
            int salesVolume = ordersMapper.selectCountByExample(ordersExample);
            List<YxStockWarning> collect = yxStockWarnings.stream().filter(yxStockWarning -> yxStockWarning.getSupplySpecId().equals(item.getSupplySpecId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)){
                YxStockWarning yxStockWarning = YxStockWarning.builder()
                        .bankerId(item.getBankerId())
                        .supplyProductId(item.getSupplyProductId())
                        .supplySpecId(item.getSupplySpecId())
                        .bankerProductId(item.getBankerProductId())
                        .bankerSpecId(item.getBankerSpecId())
                        .warningNum(item.getWarningNum())
                        .salesVolume(salesVolume)
                        .warnStatus(StockWarnStatusEnums.ING.getStatus())
                        .createTime(new Date())
                        .build();
                stockWarningMapper.insertSelective(yxStockWarning);
                //站内消息
                Example example2 = new Example(YxNotifyUrlInfo.class);
                example2.createCriteria().andEqualTo("type", 1);
                List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example2);
                if (CollectionUtils.isEmpty(notifyUrlInfos)) {
                    return;
                }
                String message = "您的商品："+item.getProductName()+"，规格库存不足，为避免影响您的订单，请及时补充库存！";
                notifyUrlInfos.stream().forEach(notifyUrlInfo -> {
                    if ("1".equals(notifyUrlInfo.getMethodType())) {
                        Map<String, String> notifyParam = new HashMap<String, String>();
                        notifyParam.put("type", "1");
                        notifyParam.put("msg", message);
                        notifyParam.put("productId", String.valueOf(item.getSupplyProductId()));
                        String result = HttpClientUtil.doPostJson(notifyUrlInfo.getUrl(), JSONObject.toJSONString(notifyParam));
                    }
                });
                //发短信
                try {
                    sendSanTong(day, item);
                } catch (Exception e) {
                    log.error("=========库存预警发短信失败==========productName:{},skuSpec:{}",item.getProductName(),item.getSupplySpecId());
                }
            }else {
                YxStockWarning yxStockWarning = collect.get(0);
                yxStockWarning.setWarningNum(item.getWarningNum());
                yxStockWarning.setWarnStatus(1);
                yxStockWarning.setSalesVolume(salesVolume);
                yxStockWarning.setCreateTime(new Date());
                stockWarningMapper.updateByPrimaryKeySelective(yxStockWarning);
                //站内消息
                Example example2 = new Example(YxNotifyUrlInfo.class);
                example2.createCriteria().andEqualTo("type", 1);
                List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example2);
                if (CollectionUtils.isEmpty(notifyUrlInfos)) {
                    return;
                }
                String message = "您的商品："+item.getProductName()+"，规格库存不足，为避免影响您的订单，请及时补充库存！";
                notifyUrlInfos.stream().forEach(notifyUrlInfo -> {
                    if ("1".equals(notifyUrlInfo.getMethodType())) {
                        log.info("===url==={}", notifyUrlInfo.getUrl());
                        Map<String, String> notifyParam = new HashMap<String, String>();
                        notifyParam.put("type", "1");
                        notifyParam.put("msg", message);
                        notifyParam.put("productId", String.valueOf(item.getSupplyProductId()));
                        String result = HttpClientUtil.doPostJson(notifyUrlInfo.getUrl(), JSONObject.toJSONString(notifyParam));
                    }
                });
                //发短信
                try {
                    sendSanTong(day, item);
                } catch (Exception e) {
                    log.error("=========库存预警发短信失败==========productName:{},skuSpec:{}",item.getProductName(),item.getSupplySpecId());
                }
            }
        });
        //查询正在报警的库存信息
        List<ProductSpecStockWarningVO> list = productMapper.selectByStockWarning(supplySpecIds);
        //警报失效的规格id
        List<Integer> loseSpecId = new ArrayList<>();
        //警报结束的规格id
        List<Integer> endSpecId = new ArrayList<>();
        //遍历正在报警的库存警报,修改警报信息
        yxStockWarnings.stream().filter(item ->item.getWarnStatus().equals(StockWarnStatusEnums.ING.getStatus())).forEach(item ->{
            List<ProductSpecStockWarningVO> collect = list.stream().filter(vo -> item.getSupplySpecId().equals(vo.getSupplySpecId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)){
                ProductSpecStockWarningVO productSpecStockWarningVO = collect.get(0);
                if (productSpecStockWarningVO.getProductStatus() != 1){
                    loseSpecId.add(item.getSupplySpecId());
                }else if (productSpecStockWarningVO.getStock() > productSpecStockWarningVO.getWarningNum()){
                    endSpecId.add(item.getSupplySpecId());
                }
            }
        });
        //修改警报失效的数据
        if (!CollectionUtils.isEmpty(loseSpecId)){
            stockWarningMapper.updateBySupplySpecIds(StockWarnStatusEnums.LOSE.getStatus(),loseSpecId);
        }
        //修改警报结束的数据
        if (!CollectionUtils.isEmpty(endSpecId)){
            stockWarningMapper.updateBySupplySpecIds(StockWarnStatusEnums.END.getStatus(),endSpecId);
        }
    }

    public void sendSanTong(String day, ProductSpecStockWarningVO item) {
        if (!"1".equals(sendStockWarnSwitch)) {
            return;
        }
        //查询今天同一个供应商有多少条库存不足提醒信息
        Example stockWarningExample = new Example(YxStockWarning.class);
        stockWarningExample.createCriteria().andEqualTo("bankerId",item.getBankerId()).andGreaterThanOrEqualTo("createTime",day);
        int i = stockWarningMapper.selectCountByExample(stockWarningExample);
        //少于10条才发短信
        if (i < 10){

            String substring = item.getProductName();
            String[] productName = {substring};
            if (productName.length > 11){
                substring = item.getProductName().substring(0, 10);
            }
            String[] phones = {item.getTel()};
            String message = "您的商品："+substring+"，规格库存不足，为避免影响您的订单，请及时补充库存！";
            String result_sto = EncryptUtil.sendSanTong(stUrl, stAccount, stPassword, phones, message, "【xxxx】");
            log.info("===大汉三通返回结果==={}", result_sto);
            if (StringUtils.isEmpty(result_sto)) {
                log.info("===大汉三通发送失败 返回结果为空===");
                return;
            }
            SanTongResponse response = JSONObject.parseObject(result_sto, SanTongResponse.class);
            log.info("===santong response==={}", response);
            if (!"0".equals(response.getResult())) {
                log.info("===大汉三通发送失败==={}", response.getDesc());
            }
        }
    }
}
